import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { FormServiceService } from '../../service/form-service.service';
import { MatDatepickerInputEvent } from '@angular/material';
import { DatePipe } from '@angular/common';
import { EChartOption } from 'echarts';
import { ToasterService } from 'app/modules/share/services/toaster.service';
import { error } from 'util';
import { differenceInCalendarDays, setHours } from 'date-fns';
import { Injector, Output, EventEmitter } from '@angular/core';
import {CandyDate} from 'ng-zorro-antd/esm2015/date-picker/lib/candy-date/candy-date.js'
interface SearchForm {
  begindate: Date | string,
  enddate: Date | string,
  exportcsv?: number | string
}

@Component({
  selector: 'm-terminal-report',
  templateUrl: './terminal-report.component.html',
  styleUrls: ['./terminal-report.component.scss'],
  providers: [DatePipe],
})

export class TerminalReportComponent implements OnInit {
  checkValue: string = '1';
  terminalOnlinePercentTip: string = "管理员管辖区域当日上线终端数量/管理员管辖区域终端总数量。"
  terminalNumTip: string = "管理员管辖区域的每日上线终端数量和离线终端数量。"
  terminalAverageUseHourCountTip: string = '管理员管辖区域每日上线终端的平均使用时长。'
  terminalUseHourCountTip: string = `管理员管辖区域每日终端使用总时长。`
  echartsForceUpdateFlag: boolean = true;
  defaultRangeValue:any=[new CandyDate(new Date()),new CandyDate(new Date())]
  today = new Date();
  maxDate = new Date();
  @ViewChild('mDateRange') mDateRange: ElementRef;
  date = new Date();
  dateRange=[]
  @Output() notifyParent: EventEmitter<any> = new EventEmitter();
  sendNotification() {
    console.log('args--:',arguments)
      // this.notifyParent.emit('Some value to send to the parent');
  }
  disabledDate = (current: Date): boolean => {
    // Can not select days before today and today
    return differenceInCalendarDays(current, this.today) > 0;
  };
  handleDateRangeChange=function(){
    console.log('change args--:',arguments)
  }

  dateRangeModel=[new Date(new Date().getTime() - 6 * 24 * 3600 * 1000),new Date()]

  searchForm: SearchForm = {
    begindate: this.datePipe.transform(new Date(new Date().getTime() - 6 * 24 * 3600 * 1000), 'yyyy-MM-dd'),
    enddate: this.datePipe.transform(new Date(), 'yyyy-MM-dd'),
    exportcsv: '',
  };
  options1: any = {};
  options2: any = {};

  constructor(
    private formService: FormServiceService,
    private datePipe: DatePipe,
    private toaster: ToasterService,
  ) {
    window['HACKER'].datePipe=datePipe;
    this.query(1);
  }

  ngAfterViewInit() {

  }
  ngOnInit() {
    // setTimeout(()=>{
    //   this['mDateRange']['nzValue']=[new CandyDate(new Date(new Date().getTime() - 6 * 24 * 3600 * 1000)),
    //     new CandyDate(new Date())]
      
    // })
    
    // alert(this['mDateRange']['nzValue'])
    window['HACKER'].setGlobalVariableForViewModel.call(this)//
    setTimeout(()=>{
      let dateRangeSpan=this.mDateRange['picker'].pickerInput.nativeElement,
      inputs=dateRangeSpan.querySelectorAll('input');

      inputs[0].value=this.searchForm.begindate
      inputs[1].value=this.searchForm.enddate
      // inputs[0].value=('”'+this.searchForm.begindate+'”').replace(/\s/g,'');
      // inputs[1].value='”'+this.searchForm.enddate+'”';
      // inputs[0].value='”'+window['HACKER'].formatTime(this['mDateRange']['nzValue'][0].nativeDate,true)+'”';
      // inputs[1].value='”'+window['HACKER'].formatTime(this['mDateRange']['nzValue'][1].nativeDate,true)+'”';

      this.mDateRange['onChangeFn']=(o)=>{
        
        this.searchForm.begindate = window['HACKER'].formatTime(o[0],true)
    this.searchForm.enddate = window['HACKER'].formatTime(o[1],true)


    let dateRangeSpan=this.mDateRange['picker'].pickerInput.nativeElement,
      inputs=dateRangeSpan.querySelectorAll('input');

      
    this.query(1)


    setTimeout(()=>{
      inputs[0].value=this.searchForm.begindate
      inputs[1].value=this.searchForm.enddate
    })

        
      }

      // [].forEach.call(inputs,(node)=>{
      //   console.log('node-------:',node)
      //   window['HACKER'].$observe(node,(box,mutationsList, observer)=>{
      //     console.log('box,mutationsList, observer',box,mutationsList, observer)
      //   })
      // })
      
      // alert(this.mDateRange['picker'].pickerInput.nativeElement)
    })
    
  }

  async changeTab(e, cb = () => { }) {

    try {
      await this.query(e.value)
      this.checkValue = e.value;
    } catch (e) {
      this.checkValue = e.value;
    }

    setTimeout(() => {
      cb();
      this.echartsForceUpdateFlag = true;
      new Function('list', 'index', 'list[index-1].click();')
        (document.querySelectorAll('.mat-button-toggle-label-content'), e.value)
    })


  }

  //快速选择时间
  quickFilter(time) {
    this.searchForm.begindate = this.datePipe.transform(new Date(new Date().getTime() - time), 'yyyy-MM-dd');
    this.searchForm.enddate = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
  }

  changeDate(eventType: string, e: MatDatepickerInputEvent<any>, type: string) {
    let date = this.datePipe.transform(e.value, 'yyyy-MM-dd');
    type === 'start' ? this.searchForm.begindate = date : this.searchForm.enddate = date;
  }

  exportExcel(isDetail=false) {
    
    let { startTime, endTime } = window['HACKER'].$bus.routeData
    // if (startTime && startTime == endTime) {
    //   this.toaster.warn('开始日期和结束日期不能是同一天', '警告');
    //   return false;
    // }
    let params: any = {};
    Object.assign(params, this.searchForm);
    params['exportcsv'] = 1;
    params={
      start_timestamp:Math.floor(new Date(params.begindate).getTime()/1000),
      end_timestamp:Math.floor(new Date(params.enddate).getTime()/1000),
      // start_timestamp:params.begindate,
      // end_timestamp:params.enddate
    }
    console.log('params---:', params)
    let idx: any = this.checkValue;
    let url = '/api/admin/report/export/' + (['pc_online_ratio', isDetail?'detail_pc_online_timedata':'pc_online_timesecs'][idx - 1]) + window['HACKER']['formateObjToParamStr'](params, true)
    // let url = '/api/report/export/' + (['pc_online_ratio', 'pc_online_timesecs'][idx - 1]) + window['HACKER']['formateObjToParamStr'](params, true)
    // let url = '/api/admin/' + (['pc_onlinestat', 'pc_onlineduration'][idx - 1]) + window['HACKER']['formateObjToParamStr'](params, true)
    console.log("urlllllll-:", url)
    // window.fetch(url).then(res => {
    window['HACKER'].fetchGet(url).then(res => {
      // console.log('resssssssssss--:', res,res.headers.get('content-disposition'))
      res.blob().then(async blob => {
        let a = document.createElement('a');
        let url = window.URL.createObjectURL(blob);
        // console.log('url and blob--:', url, blob, blob.text())
        let text = await blob.text(), jsonObj = null

        try {
          jsonObj = JSON.parse(text)
        } catch (e) {

        }
        console.log('jsonObj--:', jsonObj)
        if (jsonObj != null && (jsonObj.message || '').trim() != '') {

          window['HACKER'].APP_INSTANCE.toast.t.error(jsonObj.message, '警告')
          return false;
        }

        let filename = window['HACKER'].$bus.routeData.startTime + '至' + window['HACKER'].$bus.routeData.endTime + '终端' + (['上线', '使用时长'][idx - 1]) + '详情.csv'
        // let filename = params.begindate + '至' + params.enddate + '终端' + (['上线', '使用时长'][idx - 1]) + '详情.xlsx'
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
      })
    });

    // this.formService.data(params, this.checkValue).then((res: any) => {

    //   // if (typeof res.message === 'string') {
    //   //   this.toaster.warn(res.message, '警告');
    //   //   return;
    //   // }
    // }, error => {
    //   window.location.href = error.url;
    // });
  }

  async query(checkValue) {
    // let { startTime, endTime } = window['HACKER'].$bus.routeData
    // if (startTime && startTime == endTime) {
    //   this.toaster.warn('开始日期和结束日期不能是同一天', '警告');
    //   return false;
    // }
    function toPrecent(value) {
      if (value == 0) {
        return 0;
      }
      var str = Number(value * 100).toFixed(2);
      str += "%";
      return str;
    }
    if (!this.echartsForceUpdateFlag) {
      return false;
    }

    this.echartsForceUpdateFlag = false;

    setTimeout(() => {
      this.echartsForceUpdateFlag = true;
    })

    checkValue = checkValue || this.checkValue
    try {
      this.options1 = {
        ...this.options1,
        series: []
      }
      this.options2 = {
        ...this.options2,
        series: []
      }

    } catch (e) {

    }

    // let yesterday = this.datePipe.transform(new Function('return new Date()-86400000')(), 'yyyy-MM-dd')

    // if (new Date(this.searchForm.enddate).getTime() > new Date(yesterday).getTime()) {
    //   this.searchForm.enddate = yesterday;
    // }


    if (checkValue > 2) {
      this.checkValue = checkValue;
      return;
    }

    await this.formService.data({
      // start_timestamp: Math.floor(new Date(this.searchForm.begindate).getTime()/1),
      start_timestamp: Math.floor(new Date(this.searchForm.begindate).getTime()/1000),
      end_timestamp: Math.floor(new Date(this.searchForm.enddate).getTime()/1000)
    }, checkValue).then((res: any) => {
    // await this.formService.data(this.searchForm, checkValue).then((res: any) => {
      setTimeout(()=>{
        try{


          if('success'==res.message.toLowerCase().trim()){
            (document.querySelector('#toast-container')).remove()
          }else{
            window['$angularToast'].t.error(res.message)
          }

          
        }catch(e){}
        
      })
      // console.log('ressssssss---:',res)
      let list = res.body.list;
      // let list = res.message;
      if (typeof list === 'string') {
        this.toaster.warn(list, '警告');
        return;
      }
      let xData = [], yData = [], xData_1 = [], xData_2 = [], xData_3 = [];

      if (checkValue == '1') {
        list.forEach(item => {
          xData.push(window['HACKER'].formatTime(new Date(item.timestamp*1000),true));
          // xData.push(item.Date);
          // xData_1.push(item.Pcnum);
          xData_2.push(item.pc_online_count);
          // xData_2.push(item.OnlinePcnum);
          xData_3.push(item.pc_offline_count);
          // xData_3.push(item.OfflinePcnum);
          yData.push(item.pc_online_ratio);
          // yData.push(item.Rate);
        });
      } else if (checkValue == '2') {
        list.forEach(item => {
          xData.push(window['HACKER'].formatTime(new Date(item.timestamp*1000),true));
          // xData.push(item.Date);
          xData_1.push(item.total_pc_online_time_hours);
          // xData_1.push(item.Totalduration);
          xData_2.push(item.average_pc_online_hours);
          // xData_2.push(item.Avgduration);
        });
      }



      if (checkValue == '1') {
        this.options1 = {
          tooltip: {
            trigger: 'axis',
            formatter: function (params) {
              let tips = "";
              if (params && params.length > 0) {
                tips = params[0].name + "<br />";
                params.forEach(item => {
                  // console.log(item)
                  let percent = toPrecent(item.value);
                  tips += `${item.marker}${item.seriesName}:${percent}`
                });
              }
              return tips
            }
          },
          // legend: {
          //   bottom: '2%',
          //   data: ['终端当日上线数量', '离线终端数量'],
          //   // data: ['区域内终端总数量', '终端当日上线数量', '离线终端数量'],
          //   // data: ['终端总数量', '终端当日上线数量', '离线终端数量'],
          // },
          legend: {
            bottom: '2%',
            data: ['终端上线率'],
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xData,
          },
          yAxis: {
            axisLabel: {
              formatter: function (val) {
                let percent = toPrecent(val)
                return percent
              },
            }
          },
          series: [
            {
              name: '终端上线率',
              type: 'line',
              stack: '总量',
              data: yData,
              color: '#716acac2',
              itemStyle: {
                emphasis: { // 鼠标经过时：
                  color: "#3aa7ff",
                  borderColor: "#3aa7ff"
                }
              },
            },
          ],
        };
        this.options2 = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
              type: 'shadow',        // 默认为直线，可选为：'line' | 'shadow'
            },
          },
          legend: {
            bottom: '2%',
            data: ['终端当日上线数量', '离线终端数量'],
            // data: ['区域内终端总数量', '终端当日上线数量', '离线终端数量'],
            // data: ['终端总数量', '终端当日上线数量', '离线终端数量'],
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            data: xData,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '区域内终端总数量',
              type: 'bar',
              stack: '总量',
              // label: {
              //   show: true,
              //   position: 'insideRight',
              // },
              data: xData_1,
            },
            {
              name: '终端当日上线数量',
              type: 'bar',
              stack: '总量',
              // label: {
              //   show: true,
              //   position: 'insideRight',
              // },
              data: xData_2,
            },
            {
              name: '离线终端数量',
              type: 'bar',
              stack: '总量',
              // label: {
              //   show: true,
              //   position: 'insideRight',
              // },
              data: xData_3,
            },
          ],
        };
      } else if (checkValue == '2') {
        this.options1 = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
              type: 'shadow',        // 默认为直线，可选为：'line' | 'shadow'
            },
          },
          legend: {
            bottom: '2%',
            data: ['终端使用时长（小时）'],
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            data: xData,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '终端使用时长（小时）',
              type: 'bar',
              color: '#61A0A8',
              stack: '总量',
              // label: {
              //   show: true,
              //   position: 'insideRight',
              // },
              data: xData_1,
            }
          ],
        };
        this.options2 = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
              type: 'shadow',        // 默认为直线，可选为：'line' | 'shadow'
            },
          },
          legend: {
            bottom: '2%',
            data: ['平均使用时长（小时）'],
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            data: xData,
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              color: '#61A0A8',
              name: '平均使用时长（小时）',
              type: 'bar',
              stack: '总量',
              // label: {
              //   show: true,
              //   position: 'insideRight',
              // },
              data: xData_2,
            }
          ],
        };
      }


    });
    setTimeout(() => {
      new Function('list', 'index', 'list[index-1].click();')
        (document.querySelectorAll('.mat-button-toggle-label-content'), this.checkValue)
    })
  }

}
